package com.zl.learning.io.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class ChatServer {

    Executor executor = Executors.newCachedThreadPool();

    Set<Socket> client = new HashSet<>();

    public static void main(String[] args) {
        new ChatServer().init();
    }

    private void init() {
        try {
            ServerSocket serverSocket = new ServerSocket(666, 50);
            while (true) {
                Socket socket = serverSocket.accept();
                client.add(socket);
                executor.execute(() -> this.work(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void work(Socket socket) {
        try {
            System.out.println(socket.hashCode() + "上线了");
            InputStream in = socket.getInputStream();
            while (true) {
                byte[] bytes = new byte[1024];
                int len = in.read(bytes);
                String msg = new String(bytes, 0, len);
                System.out.println(msg);
                client.stream().filter(r -> !r.equals(socket)).forEach(r -> {
                    try {
                        OutputStream outputStream = r.getOutputStream();
                        outputStream.write(msg.getBytes());
                        outputStream.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
            try {
                socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
